<template>
  <div class="user-management">
    <el-row :gutter="20" class="mb-20">
      <el-col :span="24">
        <el-button type="primary" @click="showDialog">添加用户</el-button>
      </el-col>
    </el-row>

    <el-table :data="userList" border v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="roleTagType(row.role)">
            {{ roleDisplayName(row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser } from '@/api/setting'

// 响应式数据
const userList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const formRef = ref(null)

const form = ref({
  id: null,
  username: '',
  password: '',
  role: 'CUSTOMER'
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const roleOptions = [
  { value: 'ADMIN', label: '管理员' },
  { value: 'CUSTOMER', label: '客户' }
]

// 方法
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await getUserList()
    userList.value = res.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const showDialog = () => {
  dialogTitle.value = '添加用户'
  form.value = {
    id: null,
    username: '',
    password: '',
    role: 'CUSTOMER'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  form.value = {
    id: row.id,
    username: row.username,
    password: '',
    role: row.role
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (form.value.id) {
      await updateUser(form.value)
      ElMessage.success('更新成功')
    } else {
      await createUser(form.value)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该用户?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteUser(id)
    ElMessage.success('删除成功')
    fetchUsers()
  }).catch(() => {
    ElMessage.info('已取消')
  })
}

const roleTagType = (role) => {
  const types = {
    ADMIN: 'danger',
    CUSTOMER: 'primary'
  }
  return types[role] || ''
}

const roleDisplayName = (role) => {
  const option = roleOptions.find(item => item.value === role)
  return option ? option.label : role
}

// 生命周期
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
</style>